--1=撤消贴现，2=撤消承兑
create procedure [dbo].[sp_jiuqi_note_revoke] @opptype tinyint,@logonid int,@billid int,@errMsg varchar(255) output


AS

declare @cnt int
select @cnt=count(*) from t_cw_pj_bill_dtl where billid=@billid 

BEGIN TRANSACTION
if @opptype=1
BEGIN

	--还原银行存款
	delete from t_cw_bank_dtl where xxid in (select pjid from t_cw_pj_bill_dtl where billid=@billid) and xxtype=7 and type=1
	if @@Error<>0 or @@Rowcount<>@cnt
	begin
		select @errMsg='更新银行存款余额时发生错误，操作失败!'
		GOTO Error
	end

	delete from t_cw_bank_dtl where xxid in (select pjid from t_cw_pj_bill_dtl where billid=@billid) and xxtype=8 and type=2
	if @@Error<>0 or @@Rowcount>@cnt
	begin
		select @errMsg='删除贴现利息发生错误，操作失败!'
		GOTO Error
	end

	  --审核票据:
	  update t_cw_pj 
	  set  status=1
	  where pjid in (select pjid from t_cw_pj_bill_dtl where billid=@billid) 
		 and status=2
		 and isnull(isclose,0)=0
	  if @@Error<>0 or @@Rowcount<>@cnt
	  begin
		 select @errMsg='取消贴现发生错误，操作失败!'
		 GOTO Error
	  end

  delete from t_cw_sfk_dtl where sfkid in (select sfkid from t_cw_pj_bill where billid=@billid)
  if @@Error<>0 or @@Rowcount>100
  begin
	 select @errMsg = '删除费用报支记录发生错误,操作失败!' 
	 GOTO Error
  end		

  delete from t_cw_sfk where sfkid in (select sfkid from t_cw_pj_bill where billid=@billid) and type=13
  if @@Error<>0 or @@Rowcount>1
  begin
 	 select @errMsg = '删除费用报支记录发生错误,操作失败!' 
	 GOTO Error
  end		

  delete from t_cw_pj_bill_dtl where billid=@billid
  if @@Error<>0 or @@Rowcount<>@cnt
  begin
		select @errMsg = '删除贴现明细发生错误,操作失败!' 
		GOTO Error		
  end


  delete from t_cw_pj_bill where billid=@billid and ((u8insflag=1 and isnull(jiuqi_insert_flag,1)=1) or jiuqi_delete_flag=3)
  if @@Error<> 0or @@Rowcount<>1
  begin
		select @errMsg = '删除贴现记录发生错误,操作失败!' 
		GOTO Error		
  end

END

if @opptype=2
BEGIN
	delete from t_cw_bank_dtl where xxid in (select pjid from t_cw_pj_bill_dtl where billid=@billid) and xxtype=5 and type=2
	if @@Error<>0 or @@Rowcount<>@cnt
	begin
		select @errMsg='删除票据承兑款发生错误，操作失败!'
		GOTO Error
	end
	
	update t_cw_pj 
	set  status=(case when isnull(fkid,0)=0 and isnull(init,0)=0 then 2 else 1 end),
		   isclose=0
	where pjid in (select pjid from t_cw_pj_bill_dtl where billid=@billid) 
		 and status=2
		 and type=2 
		 and isclose=1
	if @@Error<>0 or @@Rowcount<>@cnt
	begin
		select @errMsg='更新票据承兑标志发生错误，操作失败!'
		GOTO Error		
	end

	  delete from t_cw_pj_bill_dtl where billid=@billid
	  if @@Error<>0 or @@Rowcount<>@cnt
	  begin
			select @errMsg = '删除承兑明细发生错误,操作失败!' 
			GOTO Error		
	  end


	  delete from t_cw_pj_bill where billid=@billid and ((u8insflag=1 and isnull(jiuqi_insert_flag,1)=1) or jiuqi_delete_flag=3)
	  if @@Error<>0 or @@Rowcount<>1
	  begin
			select @errMsg = '删除承兑记录发生错误,操作失败!' 
			GOTO Error		
	  end
END


COMMIT TRANSACTION
return 0

Error:
ROLLBACK TRANSACTION
return 1









